package com.biwin.module.dict.starter.controller;

import com.biwin.common.app.exception.BwBasicException;
import com.biwin.common.app.exception.BwNotFoundException;
import com.biwin.core.main.controller.BwBasicController;
import com.biwin.module.dict.api.dto.DictionaryDto;
import com.biwin.module.dict.api.enums.BwDictionaryExceptionEnum;
import com.biwin.module.dict.api.service.IDictionaryService;
import com.biwin.module.dict.api.vo.DictionaryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Dictionary Controller
 *
 * @author biwin
 * @since 0.0.1
 */
@Api(tags = "字典管理")
@RestController("Dictionary Controller")
@RequestMapping("/api/auth/dict")
public class DictionaryController extends BwBasicController {

    @Autowired
    private IDictionaryService dictionaryService;

    @ApiOperation(value = "字典列表", httpMethod = "POST")
    @PostMapping("/list")
    public void queryList() {}

    @ApiOperation(value = "添加字典", httpMethod = "PUT")
    @PutMapping("/add")
    public DictionaryVo add(@RequestBody @Validated DictionaryDto dictionaryDto) {
        try {
            dictionaryService.findByCodeDesc(dictionaryDto.getCodeDesc());
        } catch (BwNotFoundException e) {
            return dictionaryService.add(dictionaryDto);
        }
        throw new BwBasicException(BwDictionaryExceptionEnum.DICT_EXIST);
    }

    @ApiOperation(value = "修改字典", httpMethod = "POST")
    @PostMapping("/update")
    public DictionaryVo update(@RequestBody @Validated DictionaryDto dictionaryDto) {
        Assert.notNull(dictionaryDto.getId(), "id must be not null");
        Assert.notNull(dictionaryDto.getVersion(), "version must be not null");
        return dictionaryService.update(dictionaryDto);
    }

    @ApiOperation(value = "删除字典", httpMethod = "DELETE")
    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable(name = "id") Long id) {
        return dictionaryService.delete(id);
    }

    @ApiOperation(value = "启用字典", httpMethod = "POST")
    @PostMapping("/enable/{id}")
    public boolean enable(@PathVariable(name = "id") Long id) {
        return dictionaryService.enable(id);
    }

    @ApiOperation(value = "禁用字典", httpMethod = "POST")
    @PostMapping("/disable/{id}")
    public boolean disable(@PathVariable(name = "id") Long id) {
        return dictionaryService.disable(id);
    }
}
